﻿/*************************************************
Description:智能家居---娱乐功能的实现
**************************************************/
#include "entertainmentwidget.h"
#include "ui_entertainmentwidget.h"
#include <mymqtt.h>
#include <QDebug>
#include <QTimer>




EntertainmentWidget::EntertainmentWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::EntertainmentWidget)
{
    ui->setupUi(this);
    udpsocket = new QUdpSocket(this);
    tcpsocket = new QTcpSocket(this);
    state =0;
    ui->btnheart->setEnabled(false);
    c_styleOn = "QLabel{border-image:url(:/images/tool/p1.png);border:0px;}";
    c_styleOff = "QLabel{border-image:url(:/images/tool/p0.png);border:0px;}";
    ui->connectpoint->setStyleSheet(c_styleOff);
    connect(udpsocket,&QUdpSocket::readyRead,[=]()
    {
        while(udpsocket->hasPendingDatagrams())
                {
                    QByteArray data;
                    data.resize(udpsocket->pendingDatagramSize());
//                    QHostAddress host;//ip地址
//                    quint16 port;   //端口
                    udpsocket->readDatagram(data.data(), data.size(), &host, &port);//读取数据，存入data容器
                    qDebug()<< "response:"<<data.data();
                    QVariant v =data.data();
                    if(v.toString()=="yes")
                    {
                        ui->textBrowser->append("收到设备响应信息...");
                        QString list = QString("设备%1等待连接").arg(host.toString());
                        ui->listWidget->addItem(list);
                    }
                }
    });


    connect(tcpsocket,&QTcpSocket::connected,[=]()
    {
            QString str = QString("成功与[%1:%2]建立连接...").arg(host.toString()).arg(port);
            QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
            qDebug()<< "TCP连接成功";
            ui->textBrowser->append(str);
            ui->textBrowser->append(time);
            QString list = QString("设备%1连接成功").arg(host.toString());
            ui->listWidget->item(0)->setText(list);
            emit tcpconnectsignalon();
            ui->connectpoint->setStyleSheet(c_styleOn);
            ui->btnheart->setEnabled(true);
    });
    connect(tcpsocket,&QTcpSocket::disconnected,[=]()
    {
        qDebug()<< "TCP连接断开";
        ui->textBrowser->append("TCP连接断开...");
        emit tcpconnectsignaloff();
        ui->connectpoint->setStyleSheet(c_styleOff);
    });

    connect(tcpsocket,&QTcpSocket::readyRead,[=]()
    {
        receiveData();
    });


}




EntertainmentWidget::~EntertainmentWidget()
{

    tcpsocket->disconnectFromHost();
    tcpsocket->close();
    udpsocket->close();

    delete ui;
}



//设备搜索相关函数

void EntertainmentWidget::on_btnsearch_clicked()
{

    ui->textBrowser->setText("开始广播...");
    port = ui->lineEdit->text().toUInt();
    udpsocket->writeDatagram("hqdevice", QHostAddress::Broadcast, port);
    ui->textBrowser->append("广播发送成功...");

}


void EntertainmentWidget::on_btnconnect_clicked()
{
    tcpconnect();
}

void EntertainmentWidget::tcpconnect()
{

    tcpsocket->connectToHost(QHostAddress(host),port);
    ui->textBrowser->append("正在创建TCP连接...");

}

void EntertainmentWidget::on_btnadd_clicked()
{

    //请求设备状态
    QString data = "{\"type\": 1}";
    sendData(data);
    ui->textBrowser->append("发起运行状态请求...");

}


//接收服务器发送的数据
void EntertainmentWidget::receiveData()
{
    backdata = tcpsocket->readAll();
    qDebug() << "receive:" << backdata;
    //解析backdata 解json
    QJsonParseError jsonerror;
    QJsonDocument doc = QJsonDocument::fromJson(backdata.toLatin1(), &jsonerror);
    QJsonObject object = doc.object();


    //如果backdata的type是1,"up_config"是true
     if(object.value("type")==1&&object.value("up_config")==true)
     {
       //需要下发点表(发送type:2, data:flag:start,file_name,file_len)
         QFileInfo inf (":/node.json");
         QVariant v =inf.size();
         QString node = QString ("{\"type\":2,\"data\":{\"flag\":\"start\",\"file_name\":\"node.json\",\"file_len\":%1}}").arg(v.toString());
         sendData(node);
     }
     else if(object.value("type")==1&&object.value("up_config")==false)
     {
      //读data下面的配置数据(略)
     }
     else if(object.value("type")==2)//如果backdata的type是2,data:flag:start是准备接收,开始下发点表
     {
         QJsonObject obj = object.value("data").toObject();
         QString flag = obj.value("flag").toVariant().toString();
         if(flag=="start")//开始发送
         {
                 // 读取文件的全部内容
                 QString data;
                 QFile file (":/node.json");
                 if(!file.open(QIODevice::ReadOnly))
                     {
                         qDebug()<<"open read error";
                         return;
                     }
                 QTextStream stream(&file);
                 stream.setCodec("UTF-8");// 设置读取编码是UTF8
                 data = stream.readAll();
                 file.close();//关闭文件
                 tcpsocket->write(data.toLatin1());
                 ui->textBrowser->append("点表发送中...");
         }
         else if(flag=="stop")//  //如果backdata的type是2,data:flag:stop是接收完成,不做处理
         {
             ui->textBrowser->append("点表发送完成...");
         }
     }
}

//向服务器发送数据
void EntertainmentWidget::sendData(QString data)
{
    //下发数据
    tcpsocket->write(data.toLatin1());
}


void EntertainmentWidget::on_btndelete_clicked()
{
    tcpsocket->disconnectFromHost();
//    tcpsocket->close();
//    udpsocket->close();
    ui->listWidget->clear();
    state=0;
}


void EntertainmentWidget::heartbeat()
{
    QString beat = "{\"type\": 3}";
    if(tcpsocket->write(beat.toLatin1())!=-1)//发送成功才能继续发送心跳包
    QTimer::singleShot(3000, this, SLOT(heartbeat()));
}


void EntertainmentWidget::on_btnheart_clicked()
{
    if(state==0)
    {
    heartbeat();
    ui->textBrowser->append("开始发送心跳包...");
    state=1;
    }
    else
    {

    }
}
